package com.mobile.tools;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
 * 操作xml
 * @author hf
 *
 */
public class XMLUtil {
	public static void removeChildren(Node node){
		NodeList childNodes=node.getChildNodes();
		int length=childNodes.getLength();
		for(int i=length-1;i>-1;i--){
			node.removeChild(childNodes.item(i));
		}
	}
	/**
	 * 读取xml文件，生成document对象
	 * @param file							xml源文件
	 * @return
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public static Document loadDocument(String file)
		throws ParserConfigurationException,SAXException,IOException{
		//创建一个解析器工厂
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		//创建解析器
		DocumentBuilder builder=factory.newDocumentBuilder();
		//解析xml源文件，生成document对象
		Document doc=builder.parse(file);
		//去掉xml文件中作为格式化内容的空白而映射在dom树中的不必要的text node 对象
		doc.normalize();
		return doc;
	}
	/**
	 * 把dom对象保存到文件中
	 * @param dom
	 * @param file
	 * @throws TransformerConfigurationException
	 * @throws FileNotFoundException
	 * @throws TransformerException
	 * @throws IOException
	 */
	public static void saveDocument(Document dom,String file)
		throws TransformerConfigurationException,
				FileNotFoundException,
				TransformerException,
				IOException{
		//创建转化器工厂
		TransformerFactory tf=TransformerFactory.newInstance();
		//创建转化器
		Transformer transformer=tf.newTransformer();
		//设置转化器的DOCTYPE_SYSTEM和DOCTYPE_PUBLIC输出参数
		transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,dom.getDoctype().getPublicId());
		transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dom.getDoctype().getSystemId());
		//创建数据dom树的对象
		DOMSource source=new DOMSource(dom);
		//创建输出流的对象
		StreamResult result=new StreamResult();
		//创建输出的file的FileOutputStream
		FileOutputStream outputStream=new FileOutputStream(file);
		//设置dom输出流的文件输出流
		result.setOutputStream(outputStream);
		//转化器把dom内容输出为文件
		transformer.transform(source, result);
		//把流从缓存中输出
		outputStream.flush();
		//关闭输出流
		outputStream.close();
	}
}
